package kz.vokebuz.demo;

import android.os.Bundle;
import android.telephony.SmsMessage;

public class SmsMmsMsg {

	private static final int MSG_TYPE_SMS = 0;
	private static final int MSG_TYPE_MMS = 1;
	private static final int MSG_TYPE_MESSAGE = 2;

	private int msgType = -1;
	private String messageBody;
	private String msgOriginator;
	private long timeStamp;
	private boolean isStatusReport;

	SmsMmsMsg(Bundle bundle) {
		createSms(bundle);
	}
  
  SmsMmsMsg(){
  }

	private void createSms(Bundle bundle) {
		SmsMessage[] msgs = null;
		setMsgType(MSG_TYPE_SMS);

		if (bundle != null && bundle.containsKey("pdus")) {
			Object[] pdus = (Object[]) bundle.get("pdus");
			if (pdus != null) {
				msgs = new SmsMessage[pdus.length];

				for (int i = 0; i < pdus.length; i++) {
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}

				try {
					if (msgs.length == 1 || msgs[0].isReplace()) {
						setMessageBody(msgs[0].getMessageBody());
						setMsgOriginator(msgs[0].getDisplayOriginatingAddress());
						setTimeStamp(msgs[0].getTimestampMillis());
						setStatusReport(msgs[0].isStatusReportMessage());

					} else {
						// TODO check if msgs from more then one sender works
						// (when phone is off )??
						StringBuilder msgString = new StringBuilder();
						for (int i = 0; i < msgs.length; i++) {
							msgString.append(msgs[i].getMessageBody());
						}
						setMessageBody(msgString.toString());
						setMsgOriginator(msgs[0].getDisplayOriginatingAddress());
						setTimeStamp(msgs[0].getTimestampMillis());
						setStatusReport(msgs[0].isStatusReportMessage());
					}

				} catch (Exception e) {

				}
			}
		}

	}

	/**
	 * @return the msgType
	 */
	public int getMsgType() {
		return msgType;
	}

	/**
	 * @return the messageBody
	 */
	public String getMessageBody() {
		return messageBody;
	}

	/**
	 * @return the msgOriginator
	 */
	public String getMsgOriginator() {
		return msgOriginator;
	}

	/**
	 * @return the timeStamp
	 */
	public long getTimeStamp() {
		return timeStamp;
	}

	public boolean isStatusReport() {
		return isStatusReport;
	}

	/**
	 * @param msgType
	 *            the msgType to set
	 */
	public void setMsgType(int msgType) {
		this.msgType = msgType;
	}

	/**
	 * @param messageBody
	 *            the messageBody to set
	 */
	void setMessageBody(String messageBody) {
		this.messageBody = messageBody;
	}

	/**
	 * @param msgOriginator
	 *            the msgOriginator to set
	 */
	void setMsgOriginator(String msgOriginator) {
		this.msgOriginator = msgOriginator;
	}

	/**
	 * @param timeStamp
	 *            the timeStamp to set
	 */
	void setTimeStamp(long timeStamp) {
		this.timeStamp = timeStamp;
	}

	/**
	 * @param isStatusReport
	 *            the isStatusReport to set
	 */
	void setStatusReport(boolean isStatusReport) {
		this.isStatusReport = isStatusReport;
	}

}
